package adrian.sunlight.jsp.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import adrian.sunlight.jsp.*;

/**
 * Servlet implementation class Listenerservlet
 */
public class Listenerservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private RemoteEventLoggerServer Server;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Listenerservlet() {
        super();
        
        try {
			Server = new RemoteEventLoggerServer();
		} catch (IOException e) {
			System.out.println("Nu pot porni serverul: "+e.toString());
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.processRequest(request, response);
	}
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		ServletOutputStream 	out 	= response.getOutputStream();
		String 			 		action 	= request.getParameter("action").toString();
		String					msg	   	= "...";
		if(action != null){
			if(action.equals("start")){
				if(!Server.isAlive()){
					Server.open();
					
					if(Server.isStoppedByUser()){
						Server.run();
					}
					else{
						Server.start();
					}
					
					msg = Server.getLastMessage();
				}
				else{
					msg = "Serverul este deja pornit..."; 
				}
			}
			if(action.equals("get-last-message")){
				if(Server.isAlive()){
					msg = Server.getLastMessage();
				}
				else{
					msg = "Server-ul nu este pornit!";
				}
			}
			if(action.equals("get-last-messages")){
				if(Server.isAlive()){
					int num;
					if(request.getParameter("num") != null){
						num = Integer.parseInt(request.getParameter("num").toString());
					}
					else{
						num = 3;
					}
					
					msg = Server.getLastMessages(num);
				}
				else{
					msg = "Server-ul nu este pornit!";
				}
			}
			if(action.equals("stop")){
				if(Server.isAlive()){
					Server.close();
				}
				
				msg = "Serverul a fost oprit..."; 
			}
		}
		
		out.print(msg);
	}

}
